package org.easy.db;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @Description: 连接数据
 * @Author: wxl
 * @CreateTime: 2022/10/27 17:21
 */
@Slf4j
public class ConnectTemplate implements org.easy.db.DataBaseConnectTemplate {

    private DataSource dataSource;

    private JdbcTemplate jdbcTemplate;

    public ConnectTemplate (DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 连接数据库
     */
    @Override
    public void connect() {
        connect(getDataSource());
    }

    /**
     * 连接数据库
     * @param dataSource 数据库配
     */
    @Override
    public void connect(DataSource dataSource) {
        if (Objects.isNull(dataSource)) {
            dataSource = this.dataSource;
        }
        JdbcTemplate template = new JdbcTemplate(dataSource);
        setJdbcTemplate(template);
        log.info("连接数据库成功........");
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
}
